// naver ressources
var naverImg = {	btnDir:		'http://static.comic.naver.com/staticImages/COMICWEB/NAVER/img/common/',
					blank:		'blank_w.gif',
					infobulle : 'bg_nvme_layer.png',
					first :		'remote_btn_first.gif',
					first_no :	'remote_btn_first_no.gif',
					prev : 		'remote_btn_prev.gif',
					prev_no : 	'remote_btn_prev_no.gif',
					next : 		'remote_btn_next.gif',
					next_no : 	'remote_btn_next_no.gif',
					last :		'remote_btn_end.gif',
					last_no :	'remote_btn_end_no.gif',
					//top :		'remote_btn_top.gif',
					bottom :	'btn_arr.gif',
					close:		'btn_close_layer.gif',
					thmbDir:	'http://thumb.comic.naver.net/webtoon/{titleId}/thumbnail/'
				};
//plugin css rules
someCss = [];
someCss.push('body > div#doonge_console {background:salmon;border-bottom:1px solid red;padding:5px;text-align:center;}');
someCss.push('div.comicinfo div#doonge_console {clear:both;padding:25px 5px 5px 5px;text-align:left;}');

someCss.push('div.doonge_console_close {border-bottom:1px solid grey;padding-bottom:5px;margin-bottom:5px;}');
someCss.push('div.doonge_console_close span {display:block;float:left;font-weight:bold;color:black;}');
someCss.push('div.doonge_console_close div {text-align:right;}');
someCss.push('div.doonge_console_close img {cursor:pointer;}');

someCss.push('div#doonge_menu {position:absolute;top:-47px;left:650px;width:310px;height:55px;}');
someCss.push('div#doonge_menu > ul {width:310px;text-align:right;}');
someCss.push('div#doonge_menu > ul > li {display:inline-block;width:65px;height:24px;border:1px solid #BCBCBC;border-bottom:black;background:#EFEFEF;text-align:center;}');
someCss.push('div#doonge_menu > ul > li:hover {border:1px solid black;background:#333;}');
someCss.push('div#doonge_menu > ul > li > span {display:inline-block;padding:5px;}');
someCss.push('div#doonge_menu > ul > li:hover > span {color:gold;font-weight:bold;}');
someCss.push('div#doonge_menu > ul > li#plugin_logo , div#doonge_menu > ul > li#plugin_logo:hover {position:absolute;left:0px;top:0px;border:none;width:220px;background:none;text-align:right;}');

someCss.push('div#doonge_navbar {position:absolute;top:9px;left:710px;width:250px;text-align:right;font-weight:normal;}');
someCss.push('div#doonge_navbar img {vertical-align:middle;padding:0px 1px 3px 1px;}');
someCss.push('div#doonge_navbar span.translated {color:green;margin:0px 5px;}');
someCss.push('div#doonge_navbar span.not_translated {color:red;margin:0px 5px;}');

someCss.push('div#doonge_missing {position:absolute;top:95px;left:710px;width:240px;text-align:right;color:red;font-weight:normal;}');

someCss.push('ul.doonge_project_list li {padding:0px 10px 5px 0px;display:inline-block;}');
someCss.push('ul.doonge_project_list span {font-size:20px;display:inline-block;padding:3px;font-weight:bold;}');
someCss.push('ul.doonge_project_list img {width:41x;height:45px;padding:2px;background:gold;vertical-align:middle;margin-left:5px;}');
someCss.push('ul.doonge_project_list a img {opacity:0.5;background:grey;}');
someCss.push('ul.doonge_project_list a:hover img {opacity:1;background:blue;}');

someCss.push('div.dsc p.txt {height:35px;}'); //projets viewing patch.

document.getElementsByTagName("head")[0].appendChild(create('style', {textContent: someCss.join("\n")}));
someCss = [];//'unset' the var


//On what page are we ? (also double check @include).
if(/^http:\/\/comic.naver.com\/webtoon\/detail\.nhn\?titleId=/.test(window.location.href))
	{doongeDetail();}
else
	{;} //do nothing ah ah !

// - doongeDetail() handle everything for detail.nhn
function doongeDetail()	{
	//Initializing important variables and getting titleId + no.
	var rawImages = [], layerImages = [], titleId = 1, no = 0, generalURL, customURLs, split=false, refreshWatcher = false, missingImages = 0;
	var divContainer = {};
	
	divContainer.doongeConsole = create('div',{id: 'doonge_console', doonge: 'false'} );
	divContainer.doongeConsole.style.display = 'none';
	
	if(!localStorage)	{doongeAlert( create('div',{} , create('p',{textContent: 'Your browser does not support localStorage.  Consider uninstalling manually the userscript.'})) );return false;}
	
	for(divContainer.comicInfo = document.getElementById('content').firstChild;divContainer.comicInfo && (divContainer.comicInfo.nodeType != 1 || divContainer.comicInfo.className != 'section_spot');divContainer.comicInfo = divContainer.comicInfo.nextSibling)
		{
		if(divContainer.comicInfo.nodeType == 1 && divContainer.comicInfo.className == 'category_tab') {divContainer.ULCategory = true;}
		}
	if(!divContainer.comicInfo)	{doongeAlert( create('div',{} , create('p',{textContent: 'Unexpected structure found.  Check for update or desactivate the addon if the problem persists.'})) );return false;} //no section_spot, weird
	//no category_tab (completed webtoon).  Add empty one for styling purpose.
	if(!divContainer.ULCategory) {divContainer.comicInfo.parentNode.insertBefore(create('ul', {className: 'category_tab'}),divContainer.comicInfo);}
	divContainer.comicInfo = jumpTo(divContainer.comicInfo.firstChild, 'DIV', 'comicinfo');
	if(!divContainer.comicInfo) {doongeAlert( create('div',{} , create('p',{textContent: 'Unexpected structure found.  Check for update or desactivate the addon if the problem persists.'})) );return false;} //no comicInfo, weird
	//we found comicInfo, append here the console (declare it) and the menu.
	divContainer.comicInfo.appendChild(divContainer.doongeConsole);divContainer.doongeConsole.setAttribute('doonge','true');
	
	divContainer.webComic = document.getElementById('comic_view_area');
	if(divContainer.webComic) //classic webcomic
		{
		divContainer.webComic = jumpTo(divContainer.webComic.firstChild, 'DIV', 'wt_viewer');
		no = document.getElementById('content_image_0').src.split('/');
		titleId = parseInt(no[no.length-3],10);
		no = parseInt(no[no.length-2],10);
		}
	
	//Retrieve and build feedList variable.
	var feedList = localStorage.getItem('doongeFeeds');
	//localStorage.setItem('doongeFeeds', JSON.stringify([]) ); //reset feeds.
	feedList = feedList ?  JSON.parse(feedList) : [];
	if(!feedList.length || feedList.length == 0) //wrong type or empty feedList.
		{doongeAddFeed();return false;}
	
	/* MUSIC PATCH */
	// Quicktime Music, try to delete it to not get the error msg.
	var divToDelete = document.getElementById('box_player_obj');
	if(divToDelete) {divToDelete.innerHTML = '';}
	var musicPlayer = document.getElementById('bgm_player');
	var audioFile = musicPlayer ? musicPlayer.getElementsByTagName("script") : false;
	audioFile = (audioFile && audioFile.length > 0)?audioFile[0].innerHTML.split('"'):false;
	audioFile = (audioFile && audioFile.length > 1) ? audioFile[1] : false;
	if(audioFile)
		{
		musicPlayer.innerHTML = '';
		musicPlayer.setAttribute("style",'display:block;');
		var audioTag = create('audio',{height: 20, width : 200, controls: 'controls'});
		if(audioTag.canPlayType && audioTag.canPlayType('audio/mpeg'))
			{
			audioTag.appendChild(create('source',{src: audioFile, type: 'audio/mpeg'}));
			audioTag.appendChild(create('embed',{src: audioFile,height:20,width:200}));
			musicPlayer.appendChild(audioTag);
			}
		else
			{
			var dewPlayerURL = 'http://p.dandoy.free.fr/oddsquad/dewplayer.swf';
			audioTag = create('object',{type: 'application/x-shockwave-flash', data: dewPlayerURL,height:20,width:200,id: 'dewplayer',name: 'dewplayer'},
								create('param',{name: 'wmode', value: 'transparent'}),
								create('param',{name: 'movie', value: dewPlayerURL}),
								create('param',{name: 'flashvars', value: 'mp3='+audioFile+'&autostart=1&autoreplay=1'})
							);
			musicPlayer.appendChild(audioTag);
			}
		}
	
	//Quick Element Access : doongeConsole, doongeMenu, doongeLogo (li element), comicInfo (where to append the menu), comicDsc {thumbnail, title, description}, ...
	
	
	
	
	divContainer.doongeMenu = create('div', {id: 'doonge_menu'});
	divContainer.doongeMenuUL = create('ul', {style:'width:310px;text-align:right;'});
	divContainer.doongeMenu.appendChild(divContainer.doongeMenuUL);
	divContainer.doongeLogo = create('li', {id: 'plugin_logo', textContent: 'Naver Reader'} );
	divContainer.doongeMenuUL.appendChild(divContainer.doongeLogo);
	divContainer.comicInfo.appendChild(divContainer.doongeMenu);
	divContainer.missingImage = create('div', {id: 'doonge_missing'});
	divContainer.comicInfo.appendChild(divContainer.missingImage);

	
	//Build Menu.
	divContainer.doongeMenuUL.appendChild( 	create('li', {}, create('span', {textContent : 'Projects', onclick: function(){doongePrintProjects();}})));
	//divContainer.comicDsc (not a div), saveDsc and originalDsc (in case we desactivate the addon).
	divContainer.comicDsc = {'thumbnail' : false, 'title' : false, 'author' : false, 'description': false};
	var saveDsc = {};
	saveDsc.thmb = jumpTo(divContainer.comicInfo.firstChild, 'DIV', 'thmb');
	if(saveDsc.thmb) {saveDsc.a = jumpTo(saveDsc.thmb.firstChild, 'A');saveDsc.dsc = jumpTo(saveDsc.thmb.nextSibling, 'DIV', 'dsc');}
	if(saveDsc.a) {divContainer.comicDsc.thumbnail = jumpTo(saveDsc.a.firstChild, 'IMG');}
	if(saveDsc.dsc) {divContainer.comicDsc.title = jumpTo(saveDsc.dsc.firstChild, 'H2');}
	if(divContainer.comicDsc.title) {divContainer.comicDsc.author = jumpTo(divContainer.comicDsc.title.firstChild, 'EM');divContainer.comicDsc.description = jumpTo(divContainer.comicDsc.title.nextSibling, 'P');}
	saveDsc = {};
	saveDsc.thumbnail = divContainer.comicDsc.thumbnail ? divContainer.comicDsc.thumbnail.src : false;
	saveDsc.title = divContainer.comicDsc.title ? divContainer.comicDsc.title.textContent : false;
	saveDsc.description = divContainer.comicDsc.description ? divContainer.comicDsc.description.textContent : false;
	saveDsc.author = divContainer.comicDsc.author ? divContainer.comicDsc.author.textContent : false;
	
	//feedList [] {name, logo, website, url (raw),up: most recent project date we have, check: forced update in case of inactivity,
	// 				wt: [] webtoons the feed handle {id, thmb, img, title, auth, desc} }
	divContainer.projectList = create('ul', {className: 'doonge_project_list'});
	var projectList = [], JSONQueries = [];
	if(titleId > 0 && no > 0)
		{
		var CORSRequest = false;
		if(feedList[0].url && feedList[0].up && feedList[0].check && feedList[0].wt //Big feedList checking.
			&& feedList[0].wt.length && feedList[0].wt.length > 0 && typeof feedList[0].url == 'string' && parseInt(feedList[0].up) >= 0 && parseInt(feedList[0].check) > 0)
			{
			for(var j=0;j<feedList[0].wt.length;j++)
				{
				if(feedList[0].wt[j].id && feedList[0].wt[j].id == titleId)//okay they do that project, CORSRequest them.
					{
					CORSRequest = 1;
					}
				doongeAddProject(feedList[0].wt[j],0);
				}
			if(!CORSRequest && parseInt(feedList[0].check) <= doongeUTCTime())//been a while we didn't visit their feed.
				{
				CORSRequest = 2;//just update
				}
			}
		if(CORSRequest)
			{
			var currentQuery = JSONQueries.length;
			JSONQuery = createCORSRequest("get", doongeShortURL(feedList[0].url,titleId,no,feedList[0].up));
			if (JSONQuery)
				{
				JSONQuery.corsId = 0;
				JSONQuery.corsType = CORSRequest;
				JSONQuery.onerror = function (e){doongeAlert(create('p',{textContent: feedList[this.corsId].url+' could not be reached!', style: 'color:red;' }));};
				JSONQuery.onload = function(e){ if(this.readyState == 4 && this.status == 200) {doongeAnalyze(this);} }; //update feedList with the information we got, and localStorage.
				JSONQuery.send();
				}
			}
		}
	//End of doongeDetail() instructions.  Beginning of nested functions.
	// -- doongeAnalyze(JSONQuery) do what's to be done with a positive JSON response.
	function doongeAnalyze(JSONQuery)
		{
		var typeCORS = JSONQuery.corsType;
		var teamId = JSONQuery.corsId;
		var teamMessage = JSON.parse(JSONQuery.responseText);
		
		if(teamMessage.remove)
			{
			for(var i=0;i<feedList[teamId].wt.length;i++)
				{
				if(feedList[teamId].wt[i].id == titleId){feedList[teamId].wt.slice(i,1);break;}
				}
			}
		if(teamMessage.add && teamMessage.add.length)
			{
			for(var i=0;i<teamMessage.add.length;i++)
				{
				if(teamMessage.add[i].id && parseInt(teamMessage.add[i].id) > 0 && teamMessage.add[i].name && typeof teamMessage.add[i].name == 'string' &&
					teamMessage.add[i].img && typeof teamMessage.add[i].img == 'string' && teamMessage.add[i].thmb && typeof teamMessage.add[i].thmb == 'string' &&
					teamMessage.add[i].auth && typeof teamMessage.add[i].auth == 'string' && teamMessage.add[i].desc && typeof teamMessage.add[i].desc == 'string' &&
					teamMessage.add[i].up && typeof teamMessage.add[i].up == 'string' && parseInt(teamMessage.add[i].up) > 0)
					{
					var alreadyInserted = false;
					if(parseInt(teamMessage.add[i].up) > feedList[teamId].up) {feedList[teamId].up = parseInt(teamMessage.add[i].up);}
					for(var j = 0;j<feedList[teamId].wt.length;j++)
						{if(feedList[teamId].wt[j].id == teamMessage.add[i].id) {alreadyInserted = j;break;}}
					if(alreadyInserted === false)
						feedList[teamId].wt.push({id: teamMessage.add[i].id, thmb: teamMessage.add[i].thmb, img : teamMessage.add[i].img, title: teamMessage.add[i].name, auth: teamMessage.add[i].auth, desc: teamMessage.add[i].desc});
					else
						feedList[teamId].wt[alreadyInserted] = {id: teamMessage.add[i].id, thmb: teamMessage.add[i].thmb, img : teamMessage.add[i].img, title: teamMessage.add[i].name, auth: teamMessage.add[i].auth, desc: teamMessage.add[i].desc};
					}
				}
			}
		if(teamMessage.check && parseInt(teamMessage.check) > 0)
			{
			feedList[teamId].check = doongeUTCTime(parseInt(teamMessage.check));
			}
		else //default 1 week check.
			{
			feedList[teamId].check = doongeUTCTime(7);
			}
		
		if(typeCORS == 2) //we stop here.
			{
			localStorage.setItem('doongeFeeds',JSON.stringify(feedList));
			return true;
			}
		
		if(teamMessage.teamName){feedList[teamId].name = teamMessage.teamName;}
		if(teamMessage.teamLogo){feedList[teamId].logo = teamMessage.teamLogo;}
		if(teamMessage.teamURL){feedList[teamId].website = teamMessage.teamURL;}
		divContainer.doongeLogo.textContent = '';
		divContainer.doongeLogo.appendChild(create('a',{href: feedList[teamId].website},create('img',{src:feedList[teamId].logo, alt:feedList[teamId].name})));
		
		if(teamMessage.name && divContainer.comicDsc.title)
			{
			divContainer.comicDsc.title.innerHTML = '';
			divContainer.comicDsc.title.textContent = teamMessage.name;
			saveDsc.title = teamMessage.name;
			if(teamMessage.author)
				{divContainer.comicDsc.title.appendChild( create('em',{textContent:teamMessage.author}));saveDsc.author = teamMessage.author;}
			else if(divContainer.comicDsc.author)
				divContainer.comicDsc.title.appendChild( create('em',{textContent:divContainer.comicDsc.author.textContent}));
			}
		if(teamMessage.description)
			{
			divContainer.comicDsc.description.innerHTML = textContentParse(teamMessage.description).replace(/{endl}/g,'<br />');
			saveDsc.description = teamMessage.description;
			}
		if(teamMessage.translated) //woot
			{
			divContainer.navBar = create('div', {id:'doonge_navbar'},
													addNavBar(teamMessage.first,naverImg.first,naverImg.first_no),
													addNavBar(teamMessage.previous,naverImg.prev,naverImg.prev_no),
													create('span', {textContent: teamMessage.chapterName?teamMessage.chapterName:'Missing chapter name.', className:teamMessage.translated=='1'?'translated':'not_translated'}),
													addNavBar(teamMessage.next,naverImg.next,naverImg.next_no),
													addNavBar(teamMessage.last,naverImg.last,naverImg.last_no)
													);
			divContainer.comicInfo.appendChild(divContainer.navBar);
										
			if(teamMessage.translated == '1')
				{
				generalURL = teamMessage.generalUrl?teamMessage.generalUrl:false;
				customURLs = teamMessage.urls?teamMessage.urls:false;
				if(divContainer.webComic)
					{
					if(teamMessage.split) {split = teamMessage.split==1?true:false;}
					if(teamMessage.urls || (teamMessage.generalUrl &&  /{imgNumber}/.test(teamMessage.generalUrl)))
						{
						divContainer.pluginWebComic = create('div', {id:'plugin_layer', className: 'wt_viewer', style: 'z-index:10;position:absolute;top:0px;left:0px;', height:0,onclick: function(){doongeWebComicRefresh();}});
						divContainer.webComic.parentNode.appendChild(divContainer.pluginWebComic);
						if(divContainer.webComic.addEventListener)
							{
							divContainer.webComic.addEventListener('click',				function(){doongeWebComicRefresh();}	,false);
							divContainer.webComic.addEventListener('DOMNodeInserted',	function(){doongeWebComicRefresh();}	,false);
							}
						else
							{
							divContainer.webComic.attachEvent('click',					function(){doongeWebComicRefresh();});
							}
						doongeWebComicRefresh();
						}
					}
				}
			}
		localStorage.setItem('doongeFeeds',JSON.stringify(feedList));
		}
	//-- doongeAddProject(project,teamId) - push a project in the global variable projectList.
	function doongeAddProject(project,teamId)//comes from feedList, always has to check it (naver has access to it).
		{
		//{id, thmb, img, title, auth, desc}
		if(!project.id || parseInt(project.id) <= 0 || !project.thmb || typeof project.thmb != 'string' || !project.img || typeof project.img != 'string' || 
			!project.title || !project.auth  || !project.desc || typeof project.title != 'string' || typeof project.auth != 'string' || typeof project.desc != 'string')
				return false;
		var projectAlreadyInserted = -1;
		for(var i=0;i<projectList.length;i++) {if(projectList[i].id == project.id) {projectAlreadyInserted = i;break;}}
		if(projectAlreadyInserted != -1)
			{
			var replaceIt = false;
			for(var i=0;i<projectPreferences.length;i++) {if(projectPreferences[i].feedId == teamId) {replaceIt = true;break;}}
			if(replaceIt) {projectList[projectAlreadyInserted] = project;}
			}
		else
			{
			projectList.push({id: project.id,thmb: project.thmb,img: project.img,title: project.title,auth: project.auth,desc: project.desc});
			}
		}
	//-- doongeProjectDetail(projectItem) - switch comicDsc info with projectItem.getAttribute('doonge') information (projectList id).
	function doongeProjectDetail(projectItem)
		{
		if(!projectItem) //no projectItem, restore saveDsc.
			{
			if(saveDsc.thumbnail)
				{divContainer.comicDsc.thumbnail.src = saveDsc.thumbnail;}
			if(saveDsc.title)
				{divContainer.comicDsc.title.textContent = saveDsc.title;}
			if(saveDsc.description)
				{divContainer.comicDsc.description.innerHTML = textContentParse(saveDsc.description).replace(/{endl}/g,'<br />');}
			if(saveDsc.author)
				divContainer.comicDsc.title.appendChild( create('em',{textContent:saveDsc.author}));
			}
		else
			{
			projectItem = projectItem.getAttribute('doonge');
			if(projectList[projectItem].img)
				{divContainer.comicDsc.thumbnail.src = naverImg.thmbDir.replace(/{titleId}/g,projectList[projectItem].id) + projectList[projectItem].img;}
			if(projectList[projectItem].title)
				{divContainer.comicDsc.title.textContent = projectList[projectItem].title;}
			if(projectList[projectItem].desc)
				{divContainer.comicDsc.description.innerHTML = textContentParse(projectList[projectItem].desc).replace(/{endl}/g,'<br />');}
			if(projectList[projectItem].auth)
				divContainer.comicDsc.title.appendChild( create('em',{textContent:projectList[projectItem].auth}));
			}
		}
	//-- doongePrintProjects() -- sort projects by title, then doongeAlert them.
	function doongePrintProjects()
		{
		divContainer.projectList.innerHTML =  '';
		projectList.sort(function (a,b){return b.title.toLowerCase() <= a.title.toLowerCase();});
		var normalLetterLi = [];
		var specialLetterLi = create('li',{} , create('span',{textContent: '?'}) );
		var specialLetterFound = false;
		for(var i = 0; i< projectList.length; i++)
			{
			if(projectList[i].title.length > 0)
				{
				var index = 'abcdefghijklmnopqrstuvwxyz'.indexOf(projectList[i].title[0].toLowerCase());
				if(index != -1)
					{
					if(!normalLetterLi[index])
						{normalLetterLi[index] = create('li',{} , create('span',{textContent: projectList[i].title[0].toUpperCase()}) );}
					normalLetterLi[index].appendChild(projectList[i].id == titleId ? create('img',{src:naverImg.thmbDir.replace(/{titleId}/g,projectList[i].id)+projectList[i].thmb}) : create('a',{href:'http://comic.naver.com/webtoon/detail.nhn?titleId='+projectList[i].id+'&no=1'},	create('img',{src:naverImg.thmbDir.replace(/{titleId}/g,projectList[i].id)+projectList[i].thmb, doonge: i, onmouseover: function(){doongeProjectDetail(this)}, onmouseout:  function() {doongeProjectDetail()}})));
					}
				else
					{
					specialLetterFound = true;
					specialLetterLi.appendChild(projectList[i].id == titleId ? create('img',{src:naverImg.thmbDir.replace(/{titleId}/g,projectList[i].id)+projectList[i].thmb}) : create('a',{href:'http://comic.naver.com/webtoon/detail.nhn?titleId='+projectList[i].id+'&no=1'}, create('img',{src:naverImg.thmbDir.replace(/{titleId}/g,projectList[i].id)+projectList[i].thmb, doonge: i, onmouseover: function(){doongeProjectDetail(this)}, onmouseout: function(){doongeProjectDetail()}})));
					}
				}
			}
		for(var i in normalLetterLi){divContainer.projectList.appendChild(normalLetterLi[i]);}
		if(specialLetterFound){divContainer.projectList.appendChild(specialLetterLi);}
		doongeAlert(divContainer.projectList);
		}
	function doongeLayerError(){
		missingImages++;
		divContainer.missingImage.textContent = missingImages+ ' missing image'+(missingImages > 1?'s':'');
	}
	//-- doongeWebComicRefresh() : handle layer for the webcomic.
	function doongeWebComicRefresh(){
		var rawHandled = rawImages.length;
		var previousElementLoaded = true;
		if(rawHandled > 0)
			{
			var lastPreviousElementToBeLoaded = (rawImages[rawHandled-1] -1 >= 0) ? rawImages[rawHandled-1] -1 : 0;
			previousElementLoaded = document.getElementById('plugin_image_'+lastPreviousElementToBeLoaded).firstChild ?true:false;
			}
		tempElement = document.getElementById('content_image_'+rawHandled);
		if(tempElement && tempElement.complete && tempElement.height && tempElement.height > 0 && previousElementLoaded) //nice.
			{
			clearTimeout(refreshWatcher);
			if(!split)
				{
				rawImages[rawHandled] = rawHandled; //l'image rawHandled doit avoir été chargée.
				if(generalURL)
					doongeWebComicQueue(generalURL.replace(/{imgNumber}/g,(rawHandled+1)>9?(rawHandled+1):"0"+parseInt(rawHandled+1)),tempElement.width,tempElement.height);
				else if(customURLs && customURLs[rawHandled])
					doongeWebComicQueue(customURLs[rawHandled],tempElement.width,tempElement.height);
				}
			else
				{
				var firstLayer = (rawHandled == 0) ? 0 : rawImages[rawHandled-1];
				var nbSplits = Math.ceil(tempElement.height/1400);
				rawImages[rawHandled] = firstLayer + nbSplits;
				var imgNumber = (rawHandled+1)>9?(rawHandled+1):"0"+parseInt(rawHandled+1);
				
				for(var i =0; i < nbSplits-1;i++)
					{
					if(customURLs && customURLs[firstLayer+i])
						{
						doongeWebComicQueue(customURLs[firstLayer+i],tempElement.width,1400);
						}
					else if(generalURL)
						{
						var splitImgNumber = imgNumber + '_' + ((i+1)>9?(i+1):"0"+parseInt(i+1));
						doongeWebComicQueue(generalURL.replace(/{imgNumber}/g,splitImgNumber),tempElement.width,1400);
						}
					}
				if(tempElement.height%1400 != 0)
					{
					if(customURLs && customURLs[firstLayer+nbSplits-1])
						{
						doongeWebComicQueue(customURLs[firstLayer+nbSplits-1],tempElement.width,tempElement.height%1400);
						}
					else if(generalURL)
						{
						var splitImgNumber = imgNumber + '_' + ((nbSplits)>9?(nbSplits):"0"+parseInt(nbSplits));
						doongeWebComicQueue(generalURL.replace(/{imgNumber}/g,splitImgNumber),tempElement.width,tempElement.height%1400);
						}
						
					}
				}
			}
		else
			{ //img loading not complete, can't have its height => refresh in some time (2 seconds ?).
			refreshWatcher = setTimeout(doongeWebComicRefresh,2000);
			}
		}
	function doongeWebComicQueue(url,width,height){
		var lastItem = layerImages.length;
		divContainer.pluginWebComic.appendChild(create('div',{id:'plugin_image_'+lastItem, width: width, height: height}));
		layerImages[lastItem] = new Image();
		layerImages[lastItem].doonge = lastItem;
		layerImages[lastItem].onerror = function() {doongeWebComicSwap(this,false);doongeWebComicRefresh();doongeLayerError();};//permettre de passer à l'image suivante.
		layerImages[lastItem].onload = function() {doongeWebComicSwap(this,true);doongeWebComicRefresh();};
		layerImages[lastItem].src = url;
	}
	function doongeWebComicSwap(img,loaded){
		if(loaded)
			{
			document.getElementById("plugin_image_"+img.doonge).appendChild(create('img',{src: img.src}));
			return true;
			}
		else
			{
			document.getElementById("plugin_image_"+img.doonge).appendChild(create('span',{}));
			return true;
			}
	}
	//-- addNavBar(link,img_yes,img_no) : return <a><img src=yes/no></a> with the comparison being link == -1.
	function addNavBar(link,img_yes,img_no)
		{
		return (link && link != -1) ? create('a',{href: '?titleId='+titleId+'&no='+link} , create('img', {src:  naverImg.btnDir+img_yes}) ) : create('img', {src:  naverImg.btnDir+img_no});
		}
	//-- doongeAddFeed : try to add a new feed (URL that responds positively to an XMLHttpRequest ?titleId & no & up=0).
	function doongeAddFeed(){
		var datFeed = 'http://lmsodd.x10.mx/oddsquad/oss/index.php';
		var JSONQuery = createCORSRequest("get", doongeShortURL(datFeed, titleId, no, 0));
		if (JSONQuery)
			{
			JSONQuery.onerror = function() {doongeAlert(create('p',{textContent:'Feed not working!'}));};
			JSONQuery.onload = function(e){
							if(this.readyState == 4 && this.status == 200)
								{
								var parseJSON = '';
								try{ parseJSON = JSON.parse(this.responseText);}
								catch(err){doongeAlert(create('p',{textContent:'Incorrect feed! Feed not in JSON.'}));return false;}
								doongeValidateFeed(datFeed, parseJSON);
								}
							else
								doongeAlert(create('p',{textContent:'Feed not working!'}));
										};
			JSONQuery.send();
			}
	}
	//-- doongeValidateFeed : check function when a new feed is added.
	function doongeValidateFeed(datFeed,JSONResult){
		var toPush = {url: datFeed, up: '0', name: JSONResult.teamName, logo: JSONResult.teamLogo, website: JSONResult.teamURL,check: doongeUTCTime(),wt:[]};
		if(JSONResult.add && JSONResult.add.length)
			{
			for(var i=0;i<JSONResult.add.length;i++)
				{
				if(JSONResult.add[i].id && parseInt(JSONResult.add[i].id) > 0 && JSONResult.add[i].name && typeof JSONResult.add[i].name == 'string' &&
					JSONResult.add[i].img && typeof JSONResult.add[i].img == 'string' && JSONResult.add[i].thmb && typeof JSONResult.add[i].thmb == 'string' &&
					JSONResult.add[i].auth && typeof JSONResult.add[i].auth == 'string' && JSONResult.add[i].desc && typeof JSONResult.add[i].desc == 'string')
					{
					toPush.wt.push({id: parseInt(JSONResult.add[i].id), thmb: JSONResult.add[i].thmb, img : JSONResult.add[i].img, title: JSONResult.add[i].name, auth: JSONResult.add[i].auth, desc: JSONResult.add[i].desc});
					}
				}
			}
		feedList.push(toPush);
		localStorage.setItem('doongeFeeds',JSON.stringify(feedList));
		doongeDetail();
	}
	//-- doongeAlert : erase, then spawn some content in the Doonge Console, then display it.
	function doongeAlert(content){
	if(divContainer.doongeConsole.getAttribute('doonge') == 'false')
		{
		document.body.insertBefore(divContainer.doongeConsole,document.body.firstChild);
		divContainer.doongeConsole.setAttribute('doonge','true');
		}
	divContainer.doongeConsole.innerHTML = '';
	divContainer.doongeConsole.style.display = 'block';
	divContainer.doongeConsole.appendChild(create('div',{className: 'doonge_console_close', } , create('span', {textContent: 'Naver Reader Console'} ) , create('div', {} , create('img', {src: naverImg.btnDir+naverImg.close, alt: 'X', onclick: function() {divContainer.doongeConsole.innerHTML = '';divContainer.doongeConsole.style.display = 'none';}})) ));
	divContainer.doongeConsole.appendChild(content);
	}
}
/* --------------- END OF doongeDetail() (handles detail.nhn from Naver) ----------------------- */
//-- jumTo : do nodeRef.nextSibling until proper tag found, or return false.
function jumpTo(nodeRef, expectedName, expectedClass) {
	if(expectedClass)
		{
		while(nodeRef && (nodeRef.nodeName != expectedName || nodeRef.className != expectedClass)) {nodeRef = nodeRef.nextSibling;}
		}
	else
		{
		while(nodeRef && nodeRef.nodeName != expectedName) {nodeRef = nodeRef.nextSibling;}
		}
	return nodeRef ? nodeRef : false;
	}
//-- create() : creates HTML elements on the fly, from sizzlemctwizzle from userscript.org (added attachEvent for IE8 support, and doonge property not sure why).
function create() {
    switch(arguments.length) {
        case 1:
            var A = document.createTextNode(arguments[0]);
	    break;
        default:
            var A = document.createElement(arguments[0]),
                B = arguments[1];
            for (var b in B) {
				if (b.indexOf("on") == 0)
					A.addEventListener ? A.addEventListener(b.substring(2), B[b], false) : A.attachEvent(b,B[b]);
				else if (",style,accesskey,id,name,src,href,which,doonge,".indexOf("," + b.toLowerCase()) != -1)
					A.setAttribute(b, B[b]);
				else
					A[b] = B[b];
				}
            for(var i = 2, len = arguments.length; i < len; ++i)
				A.appendChild(arguments[i]);
		}
    return A;
}
//-- createCORSRequest : XMLHttpRequest Cross Origin Resource Sharing (XMLHttpRequest), from http://www.html5rocks.com/en/tutorials/cors/
function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}
//-- doongeShortURL : mere gadget to allow custom request part for an URL (instead of ?no=1&id=2&up=3). If there's a custom request format : URL?no_newname,id_newname,up_newname,request_newchar equal_newchar and_newchar [no space between separators chars].
function doongeShortURL(URL, id, no, up){
	if(URL == '') return '';
	var varNames = {no: 'no', titleId: 'id', lastUpdate: 'up'}, separators = {request:'?',equal:'=',and:'&'};
	var test = URL.indexOf('?');
	if(test != -1 && test!= URL.length) //custom varNames and optionally separators.
		{
		test = URL.substr(test+1).split(',');
		if(test.length ==3 || test.length == 4)
			{
			varNames.no = test[0];
			varNames.titleId = test[1];
			varNames.lastUpdate = test[2];
			if(test.length == 4)//custom separators
				{
				separators.request = test[3][0]?test[3][0]:separators.request;
				separators.equal = test[3][1]?test[3][1]:separators.equal;
				separators.and = test[3][2]?test[3][2]:separators.and;
				}
			}
		URL = URL.slice(0,URL.indexOf('?'));
		}
	return (URL + separators.request + varNames.no + separators.equal + no.toString() + separators.and + varNames.titleId + separators.equal + id.toString() + separators.and + varNames.lastUpdate + separators.equal + up.toString());
}
//-- doongeUTCTime : (int) date format YYYYMMDD
function doongeUTCTime(daysMore){
	if(!daysMore || daysMore < 0) var daysMore = 0;
	var today = new Date(new Date().getTime() + 1000*60*60*24*daysMore);
	return parseInt(today.getUTCFullYear() * 10000 + today.getUTCMonth() * 100 + today.getUTCDate());
}
//-- textContentParse : parse String if we want to inject it as HTML code (innerHTML).  HTML direct injection mostly avoided (maybe unused function).
function textContentParse(stringToParse){
	return String(stringToParse).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g,'&#x27;').replace(/\//g,'&#x2F;');
}
//-- doongeExtractImgNumber(url) : (int) last number found in a file name.
function doongeExtractImgNumber(url){
		var found = false, number = 0, base = 1;
		for(var i = url.length -1; i > 0; i--)
			{
			if(! /[0-9]/.test(url[i].toString()))
				{if(found) {return number;}}
			else
				{number = number + parseInt(url[i])*base;base = base*10;found=true;}
			}
		return number;
}
 